#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

//#define READ_FILE

short g_dna[16];
short g_dish[2][22][22];

void simulate()
{
	for (int line = 1; line <= 20; ++line)
	{
		for (int row = 1; row <= 20; ++row)
		{
			int n = g_dish[0][line][row] +
					g_dish[0][line-1][row] +
					g_dish[0][line+1][row] +
					g_dish[0][line][row-1] +
					g_dish[0][line][row+1];
					
			n = g_dish[0][line][row] + g_dna[n];
			n = n > 3 ? 3 : n;
			n = n < 0 ? 0 : n;
			
			g_dish[1][line][row] = n;
		}
	}
	
	memcpy(g_dish[0], g_dish[1], sizeof(g_dish[1]));
}

int main()
{
#ifdef READ_FILE
	ifstream readIn("1051.input");
	if (!readIn)
	{
		readIn.open("../1051.input");
	}
#else
#define readIn cin
#endif

	char output[4] = {'.', '!', 'X', '#'};
	memset(g_dish, 0, sizeof(g_dish));
	
	int caseCount;
	readIn >> caseCount;
	for (int i = 0; i < caseCount; ++i)
	{
		int days;
		readIn >> days;
		
		for (int n = 0; n <= 15; ++n)
		{
			readIn >> g_dna[n];
		}
		for (int line = 1; line <= 20; ++line)
		{
			for (int row = 1; row <= 20; ++row)
			{
				readIn >> g_dish[0][line][row];
			}
		}
		
		for (int currDay = 0; currDay < days; ++currDay)
		{
			simulate();
		}
		
		if (i > 0) { cout << endl; }
		
		for (int line = 1; line <= 20; ++line)
		{
			for (int row = 1; row <= 20; ++row)
			{
				cout << output[ g_dish[0][line][row] ];
			}
			cout << endl;
		}
	}
	return 0;
}
